package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {


    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    RedissonClient redissonClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1、查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);

        //2、组装成父子的树形结构

        //2.1）、找到所有的一级分类
        return entities.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0//父id为0
        ).map((menu) -> {
            //获取子分类，并设置
            menu.setChildren(getChildrens(menu, entities));
            return menu;
        }).sorted(Comparator.comparingInt(
                menu -> (menu.getSort() == null ? 0 : menu.getSort())
        )).collect(Collectors.toList());
    }


    //递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {

        return all.stream().filter(categoryEntity -> {
            //子类的父id等于父类的catid
            return categoryEntity.getParentCid() == root.getCatId();
        }).map(categoryEntity -> {
            //1、递归找到子菜单
            categoryEntity.setChildren(getChildrens(categoryEntity, all));
            return categoryEntity;
        }).sorted(Comparator.comparingInt(
                menu -> (menu.getSort() == null ? 0 : menu.getSort())
        )).collect(Collectors.toList());
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO  1、检查当前删除的菜单，是否被别的地方引用

        //逻辑删除，只是改变状态不是删除
        baseMapper.deleteBatchIds(asList);
    }

    //[2,25,225]
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);

        Collections.reverse(parentPath);


        return parentPath.toArray(new Long[parentPath.size()]);
    }

    /**
     * 级联更新所有关联的数据
     *
     * @param category
     */

    //删除分区下所有缓存
    @CacheEvict(value = "category",allEntries = true)
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }

    @Cacheable(value = "category", key = "#root.method.name", sync = true)//缓存保存
    @Override
    public List<CategoryEntity> getLeve1Categorys() {
        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("cat_level", 1));
    }

    @Cacheable(value = "category", key = "#root.method.name")//缓存保存
    @Override
    public Map<String, List<Catelog2Vo>> getCatelogJson() {

        /**
         * 解决高并发缓存问题
         * 1.解决null空结果缓存，缓存穿透
         * 2.解决多个key同时过期，解决缓存雪崩，加随机值
         * 3.解决多个同时访问同一个key，解决缓存击穿，加锁
         */

        //加入缓存逻辑，缓存中存的是json字符串，跨语言跨平台兼容
        String catelogJson = redisTemplate.opsForValue().get("catelogJson");
        if (StringUtils.isEmpty(catelogJson)) {
            //缓存中没有，查数据库
            return getCatelogJsonFromDbWithRedissonLock();
        }

        //json转为我们指定的对象
        return JSON.parseObject(catelogJson, new TypeReference<>() {
        });
    }


    //从数据库查询并封装数据,分布式锁实现
    public Map<String, List<Catelog2Vo>> getCatelogJsonFromDbWithRedissonLock() {

        //占分布式锁，redis占坑
        RLock lock = redissonClient.getLock("catelogJson-lock");
        lock.lock();
        Map<String, List<Catelog2Vo>> stringListMap;

        try {
            stringListMap = getStringListMap();
        } finally {
            lock.unlock();
        }
        return stringListMap;
    }

    //数据库查询
    public Map<String, List<Catelog2Vo>> getStringListMap() {
        //因为是同时卡在锁这里，当锁释放后其它的还会进来。从缓存中确定，所以必须处理
        String catelogJson = redisTemplate.opsForValue().get("catelogJson");
        if (!StringUtils.isEmpty(catelogJson)) {
            //redis不为空，转换为我们指定的对象
            return JSON.parseObject(catelogJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });
        }

        //一级分类
        List<CategoryEntity> leve1Categorys = getLeve1Categorys();

        Map<String, List<Catelog2Vo>> listMap = leve1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {

            //二级分类
            List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));

            List<Catelog2Vo> catelog2Vos = null;

            if (categoryEntities != null) {

                //封装二级
                catelog2Vos = categoryEntities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());

                    //找三级分类
                    List<CategoryEntity> categoryEntities3 = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", l2.getCatId()));


                    if (categoryEntities3 != null) {
                        //封装三级
                        List<Catelog2Vo.Catelog3Vo> catelog3Vos = categoryEntities3.stream().map(l3 -> new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName())).collect(Collectors.toList());

                        catelog2Vo.setCatalog3List(catelog3Vos);
                    }

                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));

        //将对象转为json存入缓存,设置过期时间
        String catelogJsonDb = JSON.toJSONString(listMap);
        redisTemplate.opsForValue().set("catelogJson", catelogJsonDb, 1, TimeUnit.DAYS);

        return listMap;
    }


    //225,25,2
    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        //1、收集当前节点id
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        }
        return paths;

    }
}